package me.zzp.resolver;

import com.google.gson.Gson;
import lombok.extern.slf4j.Slf4j;
import me.zzp.domain.Pageable;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.MethodParameter;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.support.WebDataBinderFactory;
import org.springframework.web.context.request.NativeWebRequest;
import org.springframework.web.method.support.HandlerMethodArgumentResolver;
import org.springframework.web.method.support.ModelAndViewContainer;

/**
 * @author zhangzepeng
 */
@Slf4j
@Component
public class PaginationResolver implements HandlerMethodArgumentResolver {

    @Autowired
    private Gson gson;

    @Override
    public boolean supportsParameter(MethodParameter parameter) {
        return Pageable.class.isAssignableFrom(parameter.getParameterType());
    }

    @Override
    public Object resolveArgument(MethodParameter parameter, ModelAndViewContainer container, NativeWebRequest web, WebDataBinderFactory factory) throws Exception {
        String value = web.getParameter("pageable");

        if (value != null && value.startsWith("{") && value.endsWith("}")) {
            try {
                Pageable pageable = gson.fromJson(value, Pageable.class);
                if (pageable != null) {
                    if (pageable.getSize() > 0) {
                        pageable.setPaging(true);
                    } else {
                        pageable.setPaging(false);
                        pageable.setSize(50); // default value
                    }
                }
                return pageable;
            } catch (Throwable e) {
                log.warn("parse pageable({}) failed", value);
            }
        }

        return null;
    }
}
